/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* cur=head;
        set<ListNode*> mp;
        mp.insert(head);
        while(cur)
        {
            cur=cur->next;
            if(mp.count(cur)) 
            {
                return cur;
            }
            else
            {
                mp.insert(cur);
            }
        }
        return nullptr;
    }
};